import React, { useState, useEffect, useRef } from "react";
import { PlusOutlined } from '@ant-design/icons';
import { Form, Image, Upload } from 'antd';
import { default as api } from "../lib/api"
const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
/**
 * @description 上传图片到服务器本地
 * @param { maxCount } maxCount 最大图片数量
 * @param {{url,name,uid,status}}  value 默认的图片值为对象
 */
const UploadPhotoToServer = ({
    maxCount = 5,
    onChange,
    value,
    style = Object
}) => {

    const [fileList, setFileList] = useState([]);
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };


    const handleChange = ({ file, fileList: newFileList }) => {
        setFileList(newFileList);
        if (file.status === "done" || file.status === "removed") {
            let valuesList = [];
            if (newFileList && newFileList.length > 0) {
                newFileList.forEach(item => {
                    valuesList.push({
                        url: item?.url || item.response.url,
                        name: item?.name || item.response.name,
                        uid: item?.uid || item.response.uid,
                        status: item?.status || item.response.status,
                    })
                })
            }
            onChange(valuesList);
        }


    };
    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                上传
            </div>
        </button>
    );


    const custRequest = async (options) => {
        const { file, onError, onSuccess, onProgress } = options;
        const { data, error } = await api.upload({ file: file });
        if (error) {
            onError();
            return;
        }
        onSuccess(data)
        // console.log("结果：", data)

    }


    /**@description 初始化数据 */
    const initFileList = (list) => {
        console.log("初始化数据：", list)
        if (list && list.length > 0) {
            setFileList(list.map(item => ({
                ...item, status: "done",
            })))
        }
    }

    useEffect(() => {
        if (value) {
            initFileList(value)
        }
    }, [value])


    return (
        <>
            <Upload
                listType="picture-card"
                fileList={fileList}
                // onPreview={handlePreview}
                style={{ ...style }}
                onChange={handleChange}
                maxCount={maxCount}
                customRequest={custRequest}

            >
                {fileList.length >= maxCount ? null : uploadButton}
            </Upload>

        </>
    );
};

export default UploadPhotoToServer;